<template>
  <div class="appointment-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>预约管理</span>
        </div>
      </template>
      
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="用户ID">
          <el-input v-model="queryParams.userId" placeholder="请输入用户ID" clearable />
        </el-form-item>
        <el-form-item label="车辆ID">
          <el-input v-model="queryParams.carId" placeholder="请输入车辆ID" clearable />
        </el-form-item>
        <el-form-item label="经销商ID">
          <el-input v-model="queryParams.dealerId" placeholder="请输入经销商ID" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="待确认" value="pending" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon> 查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb-2">
        <el-col :span="1.5">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon> 新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
            <el-icon><Delete /></el-icon> 批量删除
          </el-button>
        </el-col>
      </el-row>

      <el-table
        v-loading="loading"
        :data="appointmentList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="userId" label="用户ID" width="80" align="center" />
        <el-table-column prop="carId" label="车辆ID" width="80" align="center" />
        <el-table-column prop="dealerId" label="经销商ID" width="100" align="center" />
        <el-table-column label="预约时间" align="center" min-width="160">
          <template #default="scope">
            {{ formatDate(scope.row.appointmentTime) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="note" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column label="创建时间" align="center" min-width="160">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center" fixed="right">
          <template #default="scope">
            <el-button 
              link 
              type="primary" 
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button 
              link 
              type="primary" 
              @click="handleUpdateStatus(scope.row)"
              v-if="scope.row.status !== 'cancelled' && scope.row.status !== 'completed'"
            >
              状态
            </el-button>
            <el-button 
              link 
              type="danger" 
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>

    <!-- 添加/编辑预约对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      append-to-body
    >
      <el-form :model="form" ref="formRef" label-width="100px" :rules="rules">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model.number="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="车辆ID" prop="carId">
          <el-input v-model.number="form.carId" placeholder="请输入车辆ID" />
        </el-form-item>
        <el-form-item label="经销商" prop="dealerId">
          <el-select v-model="form.dealerId" placeholder="请选择经销商">
            <el-option label="经销商1" value="1" />
            <el-option label="经销商2" value="2" />
            <el-option label="经销商3" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker
            v-model="form.appointmentTime"
            type="datetime"
            placeholder="选择预约日期时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="disabledDate"
            :disabled-hours="disabledHours"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="待确认" value="pending" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="form.note" type="textarea" rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 更新状态对话框 -->
    <el-dialog
      title="更新预约状态"
      v-model="statusDialogVisible"
      width="400px"
      append-to-body
    >
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusType(statusForm.currentStatus)">
            {{ getStatusText(statusForm.currentStatus) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态" prop="newStatus">
          <el-select v-model="statusForm.newStatus" placeholder="请选择新状态">
            <el-option label="待确认" value="pending" />
            <el-option label="已确认" value="confirmed" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitStatusUpdate">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getAllAppointments, 
  addAppointment, 
  updateAppointment, 
  deleteAppointment,
  batchDeleteAppointments,
  searchAppointments,
  updateAppointmentStatus
} from '@/api/appointment'
import { Plus, Delete, Search, Refresh } from '@element-plus/icons-vue'

const loading = ref(false)
const appointmentList = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('添加预约')
const isEdit = ref(false)
const statusDialogVisible = ref(false)
const selectedIds = ref([])
const total = ref(0)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userId: '',
  carId: '',
  dealerId: '',
  status: '',
  dateRange: []
})

// 表单数据
const form = ref({
  id: undefined,
  userId: '',
  carId: '',
  dealerId: '',
  appointmentTime: '',
  status: 'pending',
  note: ''
})

// 状态表单
const statusForm = ref({
  id: '',
  currentStatus: '',
  newStatus: ''
})

// 表单规则
const rules = {
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' },
    { type: 'number', message: '用户ID必须为数字', trigger: 'blur', transform: val => Number(val) }
  ],
  carId: [
    { required: true, message: '请输入车辆ID', trigger: 'blur' },
    { type: 'number', message: '车辆ID必须为数字', trigger: 'blur', transform: val => Number(val) }
  ],
  dealerId: [
    { required: true, message: '请选择经销商', trigger: 'change' }
  ],
  appointmentTime: [
    { required: true, message: '请选择预约时间', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取预约列表
const getList = async () => {
  loading.value = true
  try {
    // 如果有查询条件，使用搜索接口
    if (hasQueryCondition()) {
      const params = {
        pageNum: queryParams.pageNum,
        pageSize: queryParams.pageSize,
        userId: queryParams.userId || undefined,
        carId: queryParams.carId || undefined,
        dealerId: queryParams.dealerId || undefined,
        status: queryParams.status || undefined,
        startDate: queryParams.dateRange && queryParams.dateRange.length > 0 ? queryParams.dateRange[0] : undefined,
        endDate: queryParams.dateRange && queryParams.dateRange.length > 1 ? queryParams.dateRange[1] : undefined
      }
      const response = await searchAppointments(params)
      appointmentList.value = response.data || []
      total.value = response.total || 0
    } else {
      // 否则获取所有预约
      const response = await getAllAppointments()
      appointmentList.value = response || []
      total.value = appointmentList.value.length
    }
  } catch (error) {
    console.error('获取预约列表失败:', error)
    ElMessage.error('获取预约列表失败')
  } finally {
    loading.value = false
  }
}

// 判断是否有查询条件
const hasQueryCondition = () => {
  return queryParams.userId || 
         queryParams.carId || 
         queryParams.dealerId || 
         queryParams.status || 
         (queryParams.dateRange && queryParams.dateRange.length > 0)
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.userId = ''
  queryParams.carId = ''
  queryParams.dealerId = ''
  queryParams.status = ''
  queryParams.dateRange = []
  handleQuery()
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString()
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'pending': return 'info'
    case 'confirmed': return 'success'
    case 'completed': return 'success'
    case 'cancelled': return 'danger'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'pending': return '待确认'
    case 'confirmed': return '已确认'
    case 'completed': return '已完成'
    case 'cancelled': return '已取消'
    default: return '未知状态'
  }
}

// 禁用日期（今天之前的日期）
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
}

// 禁用时间（工作时间外）
const disabledHours = () => {
  return Array.from({ length: 24 }).map((_, i) => i).filter(h => h < 9 || h > 18)
}

// 表格选择项变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 添加
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '添加预约'
  form.value = {
    id: undefined,
    userId: '',
    carId: '',
    dealerId: '',
    appointmentTime: '',
    status: 'pending',
    note: ''
  }
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑预约'
  form.value = { ...row }
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该预约吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteAppointment(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 条预约记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await batchDeleteAppointments(selectedIds.value.join(','))
      ElMessage.success('批量删除成功')
      getList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }).catch(() => {})
}

// 更新状态
const handleUpdateStatus = (row) => {
  statusForm.value = {
    id: row.id,
    currentStatus: row.status,
    newStatus: ''
  }
  statusDialogVisible.value = true
}

// 提交状态更新
const submitStatusUpdate = async () => {
  if (!statusForm.value.newStatus) {
    ElMessage.warning('请选择新状态')
    return
  }

  try {
    await updateAppointmentStatus(statusForm.value.id, statusForm.value.newStatus)
    ElMessage.success('状态更新成功')
    statusDialogVisible.value = false
    getList()
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  const formRef = ref(null)
  
  try {
    if (isEdit.value) {
      await updateAppointment(form.value)
      ElMessage.success('更新成功')
    } else {
      await addAppointment(form.value)
      ElMessage.success('添加成功')
    }
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getList()
}

// 页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.appointment-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mb-2 {
  margin-bottom: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 